package cn.easyutil.deploy.service;

import cn.easyutil.deploy.base.Command;
import cn.easyutil.deploy.base.CommandType;
import cn.easyutil.deploy.base.Project;
import cn.easyutil.deploy.env.SettingConfig;
import cn.easyutil.deploy.executor.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 最上层调用
 */
public class OpenApi {

    //配置文件内容
    private SettingConfig instance;

    //私有构造器
    private OpenApi() {}

    /**
     * 加载配置文件
     * @param file  配置文件路径
     * @return
     */
    public static OpenApi loadByFile(File file){
        SettingConfig config = new SettingConfig(file);
        return loadByConfig(config);
    }

    public static OpenApi loadByConfig(SettingConfig instance){
        OpenApi api = new OpenApi();
        api.instance = instance;
        return api;
    }

    /**
     * 执行指令
     * @param project 项目
     * @param command 项目中的命令
     */
    public void exec(Project project,Command command,AbstractExecutor executor){
        //获取命令类型
        CommandType type = command.getType();
        if(executor == null){
            executor = CommandExecutorBuilder.build(project);
        }
        //执行命令
        exec(project.parseCommand(type.getCommand(command)),executor);
    }

    /**
     * 执行指令
     * @param cmds
     */
    public void exec(List<String> cmds,AbstractExecutor executor){
        //执行命令
        executor.exec(cmds);
    }

    /**
     * 模糊查询项目列表
     * @param search
     * @return
     */
    public List<Project> findProjects(String search){
        List<String> projects = instance.projects(search);
        List<Project> list = new ArrayList<>();
        for (String name : projects) {
            list.add(instance.getProject(name));
        }
        return list;
    }

    /**
     * 模糊查询项目中的指令列表
     * @param project
     * @param search
     * @return
     */
    public List<Command> findCommands(Project project,String search){
        if(project == null){
            return null;
        }
        List<String> commands = instance.getCommands(project, search);
        List<Command> list = new ArrayList<>();
        for (String name : commands) {
            list.add(project.getCommand(name));
        }
        return list;
    }
}
